import {getLrc} from 'api/song.js';
import {ERR_OK} from 'api/config.js';
import {Base64} from 'js-base64';

export default class Song {
  constructor ({id, mid, name, singer, album, duration, image, url}) {
    this.id = id;
    this.mid = mid;
    this.name = name;
    this.singer = singer;
    this.album = album;
    this.duration = duration;
    this.image = image;
    this.url = url;
  }

  getLrc () {
    if (this.lrc) {
      return Promise.resolve(this.lrc);
    }
    return new Promise((resolve, reject) => {
      getLrc(this.mid).then((res) => {
        if (res.retcode === ERR_OK) {
          let lrcStr = res.lyric;
          this.lrc = Base64.decode(lrcStr);
          resolve(this.lrc);
        } else {
          reject('no lrc');
        }
      }).catch(() => {
        reject('获取歌词失败 in class');
      });
    });
  }
}

export function createSong (musicData) {
  return new Song({
    id: musicData.songid,
    mid: musicData.songmid,
    name: musicData.songname,
    singer: filterSinger(musicData.singer),
    album: musicData.albumname,
    duration: musicData.interval,
    image: `https://y.gtimg.cn/music/photo_new/T002R300x300M000${musicData.albummid}.jpg?max_age=2592000`,
    url: `http://ws.stream.qqmusic.qq.com/${musicData.songid}.m4a?fromtag=46`
  });
}

function filterSinger (list) {
  if (!list) {
    return '';
  }
  let ret = [];
  list.forEach(s => {
    ret.push(s.name);
  });
  return ret.join('/');
}
